﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using LongShare.DAO;
using MvcProject.Utils;

namespace MvcProject.Pages.Upload
{
    public partial class Upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string type = Request["type"];
            string subtype = Request["subtype"];
            string foreignKey = Request["fk"];
            string folder =  type  + "\\"+ DateTime.Now.ToString("yyyy-MM");
            if (!Directory.Exists(LongShare.Architecture.Show.AppConfig.SYS_Attachment + folder))
            {
                Directory.CreateDirectory(LongShare.Architecture.Show.AppConfig.SYS_Attachment + folder);
            }

            try
            {
                // Get the data
                HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];

                string filename = folder + "\\" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(jpeg_image_upload.FileName);
                jpeg_image_upload.SaveAs(LongShare.Architecture.Show.AppConfig.SYS_Attachment + "\\" + filename);
               
                Response.StatusCode = 200;

                string sql = "insert into t_AttachInfo(type,subtype,attachmentPath,attachmentName,ForeignKey) values(@a,@b,@c,@d,@e)";
                DBDataAccess db = new DBDataAccess();
                db.ExecuteParameterSql(sql, new string[] { type, subtype, filename.Replace("\\", "/"), jpeg_image_upload.FileName, foreignKey });
                
            }
            catch(Exception ex)
            {
                Response.Write(ex.StackTrace);
                Response.End();
            }
            finally
            {
                // Clean up
                Response.End();
                
            }
        }
    }
}